import re
from django.contrib.auth import authenticate, login, logout
from django.shortcuts import render,redirect
from django.views.generic import View
from user.models import User,Address
# 导入异步任务
from celery_tasks.tasks import send_register_active_email
from user.serializers import RegisterSerializer
from itsdangerous import TimedJSONWebSignatureSerializer
from django.conf import settings


class RegisterView(View):
    def get(self,request):
        return render(request,'register.html')

    # def post(self,request):
    #     # 1、接收数据
    #     username = request.POST.get('username')
    #     password = request.POST.get('password')
    #     password2 = request.POST.get('password1')
    #     email = request.POST.get('email')
    #     allow = request.POST.get('allow')
    #     # 2、验证数据
    #     # 2-1、验证数据完整性
    #     if not all([username,password,password2,email,allow]):
    #         return render(request,'register.html',{'errmsg':'缺失参数'})
    #     # 2-2、验证用户名格式
    #     if not re.match(r'^[a-zA-Z0-9_-]{5,20}$', username):
    #         return render(request,'register.html',{'errmsg':'格式错误'})
    #     # 2-3、验证密码格式
    #     if not re.match(r'^[a-zA-Z0-9]{8,20}$',password):
    #         return render(request,'register.html',{'errmsg':'格式错误'})
    #     # 2-4、判断两次密码是否一致
    #     if password2 != password:
    #         return render(request,'register.html',{'errmsg':'密码不一致'})
    #     # 2-5、判断是否同意协议
    #     if allow != 'on':
    #         return render(request, 'register.html',{'errmsg':'未同意协议'})
    #     # 保存数据
    #     try:
    #         user = User.objects.create_user(username=username,password=password,email=email)
    #     except:
    #         return render(request, 'register.html', {'errmsg': '保存失败'})
    #     # 将邮箱激活先设置为False,也可以在模型类中设置
    #     # user.is_active=False
    #     # user.save()
    #     # 发送邮件
    #     # 定义异步任务
    #     # 用户的信息加密方便验证
    #     tjs = TimedJSONWebSignatureSerializer(settings.SECRET_KEY, 300)
    #     token = tjs.dumps({'username': data['username'], 'email': data['email']}).decode()
    #     # 查询字符串形式发送
    #     send_register_active_email.delay(data['email'], data['username'], '?token=' + token)
    #     # 路径发送
    #     # send_register_active_email.delay(data['email'],data['username'],token)
    #     # 跳转到登录页进行登录
    #     return redirect('/user/login')
    #     # return render(request, 'register.html')

    # 序列化器注册功能实现
    def post(self,request):
        # 处理表单数据
        data = request.POST.dict()
        del data['csrfmiddlewaretoken']
        # 验证数据
        ser = RegisterSerializer(data=data)
        try:
            ser.is_valid(raise_exception = True)
        except:
            return render(request,'register.html', {'errmsg':'验证失败'})
        ser.save()
        # 发送邮件
        # 定义异步任务
        # 用户的信息加密方便验证
        tjs = TimedJSONWebSignatureSerializer(settings.SECRET_KEY,300)
        token = tjs.dumps({'username': data['username'], 'email': data['email']}).decode()
        # 查询字符串形式发送
        send_register_active_email.delay(data['email'],data['username'],'?token='+token)
        # 路径发送
        # send_register_active_email.delay(data['email'],data['username'],token)
        return redirect('/user/login')

class LoginView(View):
    def get(self, request):
        # 若登录返回首页页面
        if request.user.is_authenticated():
            return redirect('/')

        return render(request, 'login.html')

    def post(self,request):
        # 1、接收前端表单数据
        data = request.POST
        username = data.get('username')
        password = data.get('pwd')
        remembered = data.get('remember')
        # # 2、验证数据
        # # 2-1、验证数据完整性
        # if not all([username, password]):
        #     return render(request,'login.html',{'errmsg':'数据缺失'})
        # # 2-2、验证用户名格式
        # if not re.match(r'^[a-zA-Z0-9_-]{5,20}$', username):
        #     return render(request,'login.html',{'errmsg':'格式错误'})
        # # 2-3、判断用户名是否存在
        # try:
        #     user = User.objects.get(username = username)
        # except:
        #     return render(request,'login.html',{'errmsg':'用户不存在'})
        # # 2-4、判断密码是否正确
        # if not user.check_password(password):
        #     return render(request,'login.html',{'errmsg':'密码错误'})
        #
        # if not user.email_active:
        #     return render(request, 'login.html',{'errmsg':'邮箱未验证'})
        # 状态保持
        # request.session['username'] = user.username

        # 验证用户名和密码
        user = authenticate(username = username, password = password)
        if user is None:
            return render(request, 'login.html',{'errmsg':'用户名或密码错误'})
        # 判断用户邮箱是否激活
        if not user.email_active:
            return render(request, 'login.html',{'errmsg':'邮箱未验证'})
        # login方法状态保持
        login(request,user)
        # 判断是否记住用户名
        if remembered != 'on':
            request.session.set_expiry(0)
        else:
            request.session.set_expiry(None)
        # 返回首页
        # 获取不到next值，get方法给一个默认值'/',跳转到首页
        next = request.GET.get('next','/')
        return redirect(next)




class ActiveView(View):
    def get(self,request):
        # 获取验证的加密信息
        token = request.GET.get('token')
        tjs = TimedJSONWebSignatureSerializer(settings.SECRET_KEY,300)
        try:
            data = tjs.loads(token)
        except:
            return render(request,'register.html',{'errmsg':'验证失败'})
        username= data.get('username')
        email= data.get('email')
        try:
            user = User.objects.get(username = username,email =email)
        except:
            return render(request,'register.html',{'errmsg':'验证失败'})
        # 更新邮箱状态
        user.email_active = True
        user.save()
        # 返回登录页面
        return redirect('/user/login')


class LogoutView(View):
    def get(self,request):
        logout(request)
        return redirect('/')


class UserInfoView(View):
    def get(self,request):
        # 使用django自带的is_authenticated方法判断用户是否登录
        # if not request.user.is_authenticated():
        #     return redirect('/user/login')

        # 查询默认地址进行渲染
        user=request.user
        try:
            address=user.address_set.get(is_default=True)
        except:
            address=None
        # 渲染用户中心页面
        return render(request, 'user_center_info.html', {'address':address})


class AddressView(View):
    def get(self,request):
        # 获取当前用户地址信息
        user= request.user
        # 前端遍历所有地址信息
        addresses = user.address_set.all()
        # # 处理单一默认地址
        # try:
        #     address = Address.objects.get(is_default=True)
        # except:
        #     address = None
        # 渲染地址页面
        return render(request, 'user_center_site.html',{'addresses':addresses})

    def post(self,request):
        # 保存地址
        # 获取数据
        data =request.POST
        receiver = data.get('receiver')
        addr = data.get('addr')
        zip_code = data.get('zip_code')
        phone = data.get('phone')
        user =request.user
        # 验证数据
        # 验证数据完整性
        if not all([receiver, addr, zip_code, phone]):
            return render(request, 'user_center_site.html', {'errmsg':'参数缺失'})
        # 验证邮编格式
        if not re.match(r'^[0-9]\d{5}$',zip_code):
            return render(request, 'user_center_site.html', {'errmsg':'邮编格式错误'})
        # 验证手机号格式
        if not re.match(r'^1[3-9]\d{9}$',phone):
            return render(request, 'user_center_site.html', {'errmsg':'手机号格式错误'})
        # 保存地址信息
        address = Address.objects.create(user=user,receiver=receiver,addr=addr,zip_code=zip_code,phone=phone)
        # 判断是否与默认地址
        count = Address.objects.filter(is_default=True,user=user).count()
        if count == 0:
            # 添加默认地址
            address.is_default = True
            address.save()
        # return render(request, 'user_center_site.html',{'address':address})
        return redirect('/user/address')
